/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.oauth.services;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koorz.constant.GlobalConstant;
import com.koorz.modules.commission.CommissionRate;
import com.koorz.modules.user.PartyAccount;
import com.koorz.modules.user.User;
import com.koorz.oauth.model.OAuthConstants;
import com.koorz.oauth.model.OAuthRequest;
import com.koorz.oauth.model.Response;
import com.koorz.oauth.model.Token;
import com.koorz.oauth.model.UserWrapper;
import com.koorz.oauth.model.Verb;
import com.koorz.oauth.model.taobao.TaobaoToken;
import com.koorz.utils.DateUtil;
import com.koorz.utils.FileUtil;
import com.koorz.utils.IdManage;
import com.koorz.utils.LoginUtil.WeiboType;

/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-5-31 下午11:23:48
 * 版  本  号：1.0
 */
public class TaobaoService extends ApiService{
	private String API_URL_PREFIX = "https://eco.taobao.com/router/rest";
	
	@SuppressWarnings("rawtypes")
	@Override
	public User bindUser(Token objClass) {
		TaobaoToken accessToken = (TaobaoToken) objClass;
		User user  = null;
		UserWrapper userWrapper = getUserInfo(accessToken.getAccessToken());
		user = User.dao.findFirst("select u.* from user as u inner join party_account as pa on pa.user_id=u.id where pa.account_id=?",userWrapper.getUid());	
		if (user == null) {
			user = new User();
			String userId = IdManage.nextId(IdManage.USER);
			user.set("id", userId);
			user.set("nickname",userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature", userWrapper.getDesc());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), userId);
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.set("create_time", DateUtil.getNowDateTime());
			user.set("score", 0);
			user.set("online", 1);
			
			CommissionRate rate = CommissionRate.dao.findFirst("select * from commission_rate where type=?", CommissionRate.Type.DEFAULT.ordinal());
			user.set("account_balance", 0.0);
			user.set("commission_rate", rate.getDouble("commission_rate"));
			user.set("type", User.UserType.SELF.ordinal());
			user.set("freeze", User.IsFreeze.UNFREEZE.ordinal());
			user.set("role_id", User.DEFAULT_ROLE);
			user.save();
			
			PartyAccount account = new PartyAccount();
			account.set("id", IdManage.nextId(IdManage.PARTYACCOUNT));
			account.set("user_id", userId);
			account.set("account_id", userWrapper.getUid());
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", accessToken.getRefreshToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.set("type", WeiboType.TAOBAO.ordinal());
			account.save();
			
			user.put("platform",WeiboType.TAOBAO.ordinal());
		} else {
			user.set("nickname", userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature", userWrapper.getDesc());
			user.set("online", 1);
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.update();
			
			PartyAccount account = PartyAccount.dao.findFirst("select id,user_id,access_token,expires_in from party_account where user_id=? and account_id=?", 
					new Object[]{user.getStr("id"),userWrapper.getUid()});
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", accessToken.getRefreshToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.update();
			
			user.put("platform",WeiboType.TAOBAO.ordinal());
		}
		return user;
	}

	@Override
	protected UserWrapper wapperUser(JSONObject obj) {
		UserWrapper user = new UserWrapper();
    	user.setAvatar(obj.getString("avatar"));
    	user.setAvatarLarge(obj.getString("avatar"));
    	//m--男，f--女,n--未知
    	if("m".equals(obj.getString("sex"))){
    		user.setGender(1);
    	}else if("f".equals(obj.getString("sex"))){
    		user.setGender(0);
    	}else {
    		user.setGender(2);
    	}
    	user.setNickname(obj.getString("nick"));
    	user.setUid(obj.getString("user_id"));
		return user;
	}

	@Override
	protected List<UserWrapper> wapperUsers(JSONArray array) {
		return null;
	}

	public UserWrapper getUserInfo(String accessToken) {
		OAuthRequest request = createRequest(Verb.POST, API_URL_PREFIX);
		request.addBodyParameter("method", "taobao.user.buyer.get");
		request.addBodyParameter("format", "json");
		request.addBodyParameter("v", "2.0");
		request.addBodyParameter("fields","user_id,nick,sex,avatar");
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONObject jsonObj = JSON.parseObject(response.getBody());
	    	return wapperUser(jsonObj.getJSONObject("user_buyer_get_response").getJSONObject("user"));
	    }
	    return null;
	}
}
